const { Unauthorized } = require("http-errors");
const { verifyToken } = require("../utils/jwt");
const { User: db } = require("../models");
const { whiteList } = require("../config/app");
const { getKey } = require("../utils/redis");

module.exports = async (req, res, next) => {
  try {
    // 接口白名单
    const url = new URL(req.url, req.protocol + "://" + req.get("host"))
      .pathname;
    if (whiteList.indexOf(url) !== -1) return next();

    const token = req.headers.authorization?.split(" ").pop();

    if (!token) throw new Unauthorized("当前接口需要认证才能访问！");

    const decoded = verifyToken(token);

    if (!decoded) throw new Unauthorized("token已过期，请重新登陆");

    const { userId } = decoded;

    const user = await db.findOne({ where: { id: userId } });

    if (!user) throw new Unauthorized("用户不存在！");

    console.log();

    const sessionToken = await getKey(`token_${user.username}`);

    if (token !== sessionToken)
      throw new Unauthorized("无效的token,请重新登陆！");

    req.user = user;

    next();
  } catch (error) {
    next(error);
  }
};
